#include "util.hpp"
#include <functional>
#include <vector>
#include <unistd.h>

#define INIT_CBS(cbs)              \
    do                             \
    {                              \
        cbs.push_back(printLog);   \
        cbs.push_back(download);   \
        cbs.push_back(executeSql); \
    } while (0)

#define EXEC_OTHER(cbs)    \
    do                     \
    {                      \
        for (auto e : cbs) \
        {                  \
            e();           \
        }                  \
    } while (0)

using func_t = function<void()>;

int main()
{
    setNonBlock(0);
    vector<func_t> cbs;
    INIT_CBS(cbs);
    char buf[1024] = {0};
    for (;;)
    {
        int ret = read(0, buf, sizeof(buf) - 1);
        if (ret == 0)
        {
            cout << "read end!!!" << endl;
            break;
        }
        else if (ret > 0)
        {
            buf[ret - 1] = 0; // 去掉'\n'
            cout << "echo# " << buf << endl;
        }
        else
        {
            // ret < 0 ,可能出错了,可能没出错只是以错误的形式返回而已
            if (errno == EAGAIN)
            {
                cout << "没有出错,只是轮询没有数据!!!" << endl;
                EXEC_OTHER(cbs);
            }
            else if (errno == EINTR)
            {
                continue;
            }
            else
            {
                cout << "ret: " << ret << "  "
                     << "errno: " << errno << "  " << strerror(errno) << endl;
                break;
            }
        }
        sleep(1);
    }
    return 0;
}